<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class EducationalDegrees extends CI_Model {

	function __construct() {
        parent::__construct();
    }

    public function exists($educationalDegree) {
    	$id = self::getId($educationalDegree);
    	return ($id > 0);
    }

    public function getAll() {
    	$sql = "SELECT " .
			   "ed.EducationalDegreeId AS `Id`, " .
			   "ed.EducationalDegree " .
			   "FROM " .
			   "educationaldegrees AS ed " .
			   "ORDER BY " .
			   "ed.EducationalDegree";

		$query = $this->db->query($sql);
		return $query->result_array();
    }			

    public function getId($educationalDegree) {
    	$id = 0;

    	$sql = "SELECT " . 
    		   "ed.EducationalDegreeId AS `Id` " .
    		   "FROM " .
    		   "educationaldegrees AS ed " .
    		   "WHERE " .
    		   "(ed.`EducationalDegree` LIKE " . $this->db->escape((string) $educationalDegree) . ")";

    	$query = $this->db->query($sql);
    	if ($query->num_rows() > 0) {
    		$row = $query->row_array();
    		$id = $row['Id'];
    	}

    	return $id;
    }

    public function save($updates) {
    	$saved = true;

    	$this->db->trans_begin();

    	foreach ($updates as $update) {
    		$sql = '';
    		$params = array();

    		if ($update->RowState == 'added') {
    			$sql = "INSERT INTO `educationaldegrees` " .
    				   "(`EducationalDegree`, `DateCreated`) " .
    				   "VALUES " .
    				   "(?, NOW())";

    			$params = array( $update->EducationalDegree );
    		}
    		else if ($update->RowState == 'modified') {
    			$sql = "UPDATE `educationaldegrees` SET " .
    				   "`EducationalDegree` = ? " .
    				   "WHERE " .
    				   "(`EducationalDegreeId` = ?)";

    			$params = array( $update->EducationalDegree, $update->Id );		
    		}
    		else if ($update->RowState == 'deleted') {
    			$sql = "DELETE FROM `educationaldegrees` WHERE (`EducationalDegreeId` = ?)";

    			$params = array( $update->Id );	
    		}
    		else {

    		}

    		if (trim($sql) != '') $this->db->query($sql, $params);
    	}

    	if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $saved = false;
        }
        else {
            $this->db->trans_commit();
        }

    	return $saved;
    }
}